package com.bjesc_b2c.app.appraiset.mvp.view.activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.adapter.ImageTagAdapter;
import com.bjesc_b2c.app.appraiset.adapter.MyAdapter;
import com.bjesc_b2c.app.appraiset.adapter.SpacesItemDecoration;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.bean.ImageBean;
import com.bjesc_b2c.app.appraiset.bean.ImageDirBean;
import com.bjesc_b2c.app.appraiset.bean.ItemViewBean;
import com.bjesc_b2c.app.appraiset.listener.OnChangeListener;
import com.bjesc_b2c.app.appraiset.listener.OnItemClickListener;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.utils.BitmapUtil;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.utils.QRCodeUtil;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.util.MapUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.MultiItemTypeAdapter;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

import static android.os.Environment.getExternalStorageDirectory;
import static com.bjesc_b2c.app.appraiset.utils.BitmapUtil.getImage;
import static com.bjesc_b2c.app.appraiset.utils.BitmapUtil.saveImgWithName;
public class ImageSelectActivity extends BaseActivity implements OnItemClickListener,
        OnChangeListener, View.OnClickListener {
    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_CUT = 2;// 结果

    private ArrayList<Uri> imageUris;
    private String imageName = "";
    private String shareText;
    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<ImageDirBean> imageDirBeans = new ArrayList<>();
    /**
     * 图片数量
     */
    private int totalCount = 0;
    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashSet<String> mDirPaths = new HashSet<>();
    /**
     * 所有的图片
     */
    private List<ImageBean> mImages = new ArrayList<>();
    /**
     * 选中的图片集合
     */
    private ArrayList<ImageBean> mSelectImages = new ArrayList<>();
    /**
     * 最大的图片数
     */
    private int maxImageCount = 9;
    /**
     * 屏幕高度
     */
    private int mScreenHeight;
    /**
     * 用来存储选中的文件
     */
    private File mSelectFile;
    /**
     * 当PopupWindow显示或者消失时改变背景色
     */
    private WindowManager.LayoutParams lp;
    /**
     * 拿到传过来的值，测试选择图片
     */
    private int select;
    /**
     * 存储拍照和选中的图片
     */
    private File file;
    private MyThread mThread;
    private RecyclerView rcyImageSelect;
    private RecyclerView rcytagSelect;
    private ArrayList<String> imageList;
    private int selectType = 0;
    private TextView titleTv;
    private GridLayoutManager gridLayoutManager;
    private int[] resID = {R.mipmap.tag_0, R.mipmap.tag_1, R.mipmap.tag_2, R.mipmap.tag_3, R.mipmap.tag_4, R.mipmap.tag_5};
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            cancelLoading();
            if (msg.what == 0x110) {
                setData();        //绑定数据
            } else {
                if (mThread != null && !mThread.isInterrupted()) {
                    mThread.isInterrupted();
                    shareImages(ImageSelectActivity.this, imageUris);
                    finish();
                }
            }
        }
    };

    private MyAdapter mAdapter;

    @Override
    protected int getLayout() {
        return R.layout.activity_image_select;
    }

    @Override
    protected void initEventAndData() {
        select = 9;
        imageList = getIntent().getStringArrayListExtra("imageUrls");
        maxImageCount = select;
        rcyImageSelect = (RecyclerView) findViewById(R.id.rcyView_imageSelect);
        rcytagSelect = (RecyclerView) findViewById(R.id.rcyView_tagSelect);
        findViewById(R.id.tv_share).setOnClickListener(this);
        titleTv = (TextView) findViewById(R.id.tv_title);
        if (getIntent().getStringExtra("shareUrl") != null) {
            Bitmap mBitmap = QRCodeUtil.createQRCodeBitmap(getIntent().getStringExtra("shareUrl"), 480, 480);
            saveImgWithName(mBitmap, "qr_code.jpg", "images/", this);
            String path = Environment.getExternalStorageDirectory() + "/Pgs/cache/images/qr_code.jpg";
            imageList.add(4, path);
        }
        shareText = getIntent().getStringExtra("shareText");
        gridLayoutManager = new GridLayoutManager(this, 3);
        rcyImageSelect.setLayoutManager(gridLayoutManager);
        rcytagSelect.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        titleTv.setText("已选择"+mSelectImages.size()+"张");
        getImageList();
        file = new File(getExternalStorageDirectory(), "temp.jpg");
        ArrayList list = new ArrayList<>();
        for (int i = 0; i < resID.length; i++) {
            ItemViewBean bean = new ItemViewBean("", resID[i]);
            list.add(bean);
        }
        ImageTagAdapter adapter = new ImageTagAdapter(this, R.layout.image_select_tag_item, list);
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, final int position) {
                selectType = position;
                if (position != 0) {
                    for (int i = 0; i < mSelectImages.size(); i++) {
                        mSelectImages.get(i).setImagetag(resID[position]);
                    }
                    mAdapter.notifyData(mSelectImages);
                }else {
                    for (int i = 0; i < mSelectImages.size(); i++) {
                        mSelectImages.get(i).setImagetag(0);
                    }
                    mAdapter.notifyData(mSelectImages);
                }
            }
            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        rcytagSelect.setAdapter(adapter);
    }

    @Override
    protected void createPresenter() {

    }

    private void setData() {
        mAdapter = new MyAdapter(this, maxImageCount, mImages, this, this);
        rcyImageSelect.setAdapter(mAdapter);
        rcyImageSelect.addItemDecoration(new SpacesItemDecoration(2));
//      tvImageCount.setText(totalCount + "张");
    }

    private void getImageList() {
        //判断是否有内存卡
//        if (!Environment.getExternalStorageState().equals(
//                Environment.MEDIA_MOUNTED)) {
//            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
//        } else {
         showLoading();
            if (imageList != null && imageList.size() > 0) {
                mImages.clear();
                for (int i = 0; i < imageList.size(); i++) {
                    Logger.d("imageList==" + imageList.get(i));
                    ImageBean imbean = new ImageBean();
                    imbean.setPath(imageList.get(i));
                    if (i < 9) {
                        imbean.setSelect(true);
                    }
                    mImages.add(imbean);
                }
                mHandler.sendEmptyMessage(0x110);
            }
//        }
    }

    @Override
    public void onItemClickListener(View view, int position) {
        if (position != 0) {
            if (maxImageCount == 1) {
                clipPhoto(Uri.fromFile(new File(mImages.get(position).getPath())), PHOTO_REQUEST_CUT);//开始裁减图片
            } else {
//                Toast.makeText(this, position + "", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void OnChangeListener(int position, boolean isChecked) {
        if (isChecked) {
            mImages.get(position).setSelect(true);
            if (!contains(mSelectImages, mImages.get(position))) {
                if (selectType > 0) {
                    mImages.get(position).setImagetag(resID[selectType]);
                }
                mSelectImages.add(mImages.get(position));
//                if (mSelectImages.size() == maxImageCount) {
                mAdapter.notifyData(mSelectImages);
//                }
            }
        } else {
            mImages.get(position).setSelect(false);
            if (contains(mSelectImages, mImages.get(position))) {
                mSelectImages.remove(mImages.get(position));
//                rcyImageSelect.getChildAt(position).findViewById(R.id.imageType).setVisibility(View.GONE);
//                if (mSelectImages.size() == maxImageCount - 1) {
                mAdapter.notifyData(mSelectImages);
//                }
            }
        }
        titleTv.setText("已选择"+mSelectImages.size()+"张");
    }

    private boolean contains(List<ImageBean> list, ImageBean imageBean) {
        for (ImageBean bean : list) {
            if (bean.getPath().equals(imageBean.getPath())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_share) {
//            StorageUtils.deleteDirectory(getExternalStorageDirectory() + "/Pgs/");
            if (mSelectImages.size() != 0) {
                showLoading();
                mThread = new MyThread();
                mThread.start();
                String carID = CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf());
                shareSuc(carID);
            } else {
                Toast.makeText(this, "请选择至少一张图片", Toast.LENGTH_SHORT).show();
            }
        }
        if (v.getId() == R.id.iv_return){
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
            switch (requestCode) {
                case PHOTO_REQUEST_CAMERA:
                    clipPhoto(Uri.fromFile(file), PHOTO_REQUEST_CAMERA);//开始裁减图片
                    break;
                case PHOTO_REQUEST_CUT:
                    Bitmap bitmap = data.getParcelableExtra("data");
                    Intent intent = new Intent();
                    ByteArrayOutputStream bs = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bs);
                    byte[] bitmapByte = bs.toByteArray();
                    intent.putExtra("bitmap", bitmapByte);
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
            }
    }

    private void clipPhoto(Uri uri, int type) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setAction("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");// mUri是已经选择的图片Uri
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);// 输出图片大小
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        if (type == PHOTO_REQUEST_CAMERA) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                if (mSelectImages.size() > 0) {
                    for (int i = 0; i < mSelectImages.size(); i++) {
                        if (mSelectImages.get(i).getPath().startsWith("http")) {
                            String name[] = mSelectImages.get(i).getPath().split("/");
                            imageName = name[3] + "_" + name[4] + ".jpg";
                            boolean saveTrue = downloadLyWithName(mSelectImages.get(i).getPath(), imageName, "images/", ImageSelectActivity.this);
                            if (saveTrue) {
                                Logger.d("imageName===" + imageName);
                                mSelectImages.get(i).setPath(getExternalStorageDirectory() + "/Pgs/cache/images/" + imageName);
                            }
                        } else {
                            if (!mSelectImages.get(i).getPath().contains("qr_code.jpg") && selectType > 0) {
                                Bitmap bitmap1 = BitmapFactory.decodeFile(mSelectImages.get(i).getPath());
                                Bitmap waterBitmap = BitmapFactory.decodeResource(ImageSelectActivity.this.getResources(), resID[selectType]);
                                bitmap1 = BitmapUtil.createWaterMaskLeftBottom(ImageSelectActivity.this, bitmap1, waterBitmap, 20, 0);
                                imageName = imageName + "_" + selectType;
                                saveImgWithName(bitmap1, imageName, "images/", ImageSelectActivity.this);
                                mSelectImages.get(i).setPath(getExternalStorageDirectory() + "/Pgs/cache/images/" + imageName);
                            }
                        }
                    }
                }
//                File file = new File(getExternalStorageDirectory() + "/Pgs/cache/" + "images/");
//                File[] files = file.listFiles(new FileFilter() {
//                    @Override
//                    public boolean accept(File pathname) {
//                        if (pathname.getName().endsWith(".jpg")) {
//                            return true;
//                        }
//                        return false;
//                    }
//                });
                //                for (File f : files) {
//                    imageUris.add(Uri.fromFile(f));
//                    Logger.d("imageUris=="+Uri.fromFile(f));
//                }
                imageUris = new ArrayList<Uri>();
                for (int i = 0; i < mSelectImages.size(); i++) {
                    imageUris.add(Uri.fromFile(new File(mSelectImages.get(i).getPath())));
//                    Logger.d("mSelectImages==" + mSelectImages.get(i).getPath());
//                    Logger.d("fromFile==" + Uri.fromFile(new File(mSelectImages.get(i).getPath())));
                }
                mHandler.sendEmptyMessage(0x111);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 保存带名称的图片
    public Boolean downloadLyWithName(String url, String imgName, String fileName, Context mContext) throws Exception {
        File file = new File(getExternalStorageDirectory() + "/Pgs/cache/" + "images/" + imgName);
        if (file.exists()) {
            Logger.d("file.exists()");
            Bitmap bitmap1 = null;
            if (selectType > 0) {
                bitmap1 = BitmapFactory.decodeFile(getExternalStorageDirectory() + "/Pgs/cache/" + "images/" + imgName);
                Bitmap waterBitmap = BitmapFactory.decodeResource(mContext.getResources(), resID[selectType]);
                bitmap1 = BitmapUtil.createWaterMaskLeftBottom(ImageSelectActivity.this, bitmap1, waterBitmap, 20, 0);
                imageName = imgName + "_" + selectType;
                saveImgWithName(bitmap1, imageName, fileName, mContext);
            }
            return true;
        }
        Bitmap bitmap1 = null;
        byte[] data1 = getImage(url);
        if (data1 != null) {
            bitmap1 = BitmapFactory.decodeByteArray(data1, 0, data1.length);// bitmap
            if (selectType > 0) {
                Bitmap waterBitmap = BitmapFactory.decodeResource(mContext.getResources(), resID[selectType]);
                bitmap1 = BitmapUtil.createWaterMaskLeftBottom(ImageSelectActivity.this, bitmap1, waterBitmap, 20, 0);
                imageName = imgName + "_" + selectType;
            }
            saveImgWithName(bitmap1, imageName, fileName, mContext);
            return true;
        } else
            return false;
    }


    public void shareImages(Context context, ArrayList<Uri> imageUris) {
        Intent shareIntent = new Intent();
        // 1 Finals 2016-11-2 调用系统分享
        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
        shareIntent.setType("image/*");
        // 3 Finals 2016-11-2 指定选择微信。
        ComponentName mComponentName = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        shareIntent.setComponent(mComponentName);
        shareIntent.putExtra("Kdescription",shareText); //微信分享页面，图片上边的描述
        // 4 Finals 2016-11-2 开始分享。
        context.startActivity(Intent.createChooser(shareIntent, "分享图片"));
    }
    private void shareSuc(String carID){
        HashMap<String, Object> build = new MapUtil()
                .put("car_id",carID)
                .build();
        RxRequest.request(ShowType.DISMISS, RxRequest.getClient(mContext, build).create(IApiActivityRequest.class).shareCode(),
                new BaseSubscriber<TokenBean>(mContext) {
                    @Override
                    public void onSuccess(TokenBean o) {

                    }
                    @Override
                    public void onFailure(Throwable e) {

                    }
                });

    }
}
